package com.liam.websocket.controller;


import com.liam.websocket.netty.NettyConfig;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;

@Controller
@RequestMapping("/chat")
public class ChatRoomController {


    @GetMapping("/index")
    public String index() {
        return "pages/websocket";
    }

    @GetMapping("/online")
    public void online(){
        NettyConfig.group.forEach(channel -> {
            System.out.println(channel.id().asShortText() +"\t" + channel.id().asLongText() +"\t" +channel.id().toString());
        });
        System.out.println("在线人数" + NettyConfig.group.size());
    }
    /**
     * 推送给所有用户
     * @param msg
     */
    @GetMapping("/pushAll")
    public void pushToAll(@RequestParam("msg") String msg){
        TextWebSocketFrame tws = new TextWebSocketFrame("all:"+new Date().toString() + "," + msg);
        NettyConfig.group.writeAndFlush(tws);
    }

    @GetMapping("/pushOne")
    public void pushMsgToOne(@RequestParam("userId") String userId,@RequestParam("msg") String msg){
        TextWebSocketFrame tws = new TextWebSocketFrame("单聊:"+new Date().toString() + "," + msg);
        Channel c = NettyConfig.userChannelMap.get(userId);
        c.writeAndFlush(tws);

    }
}
